import { videoService } from "../../services/videoService"; // 引入 videoService 来与后端交互

export class KnowledgePage {
  constructor() {
    this.dom = null;
    this.videoList = [];
  }

  async render() {
    this.dom = document.createElement("div");
    this.dom.classList.add("container", "mt-4");

    const html = `
      <div class="row" id="video-gallery">
        <!-- 视频卡片会插入到这里 -->
      </div>
    `;

    this.dom.innerHTML = html;
    await this.loadVideos(); // 加载视频
    return this.dom;
  }

  async loadVideos() {
    try {
      const res = await videoService.getAll(); // 从后端获取视频数据
      this.videoList = res || [];
      this.renderVideos(); // 渲染视频
    } catch (err) {
      console.error("加载视频失败", err);
    }
  }

  renderVideos() {
    const gallery = this.dom.querySelector("#video-gallery");
    gallery.innerHTML = ""; // 清空当前展示

    this.videoList.forEach((video) => {
      const videoCard = document.createElement("div");
      videoCard.classList.add("col-md-6", "mb-4");

      videoCard.innerHTML = `
        <div class="card">
          <div class="card-body">
            <h5 class="card-title">${video.videoTitle}</h5>
            <p class="card-text">${video.videoContent}</p>
            <p class="card-text"><small class="text-muted">创建时间: ${
              video.createTime
            }</small></p>
            <div class="ratio ratio-16x9">
              <!-- 嵌入视频 -->
              <iframe 
                src="//player.bilibili.com/player.html?isOutside=true&bvid=${this.extractBilibiliVideoId(
                  video.videoLink
                )}&page=1" 
                scrolling="no" 
                border="0" 
                frameborder="no" 
                framespacing="0" 
                allowfullscreen="true"
                title="${video.videoTitle}">
              </iframe>
            </div>
          </div>
        </div>
      `;

      gallery.appendChild(videoCard);
    });
  }

  // 从B站链接中提取视频ID
  extractBilibiliVideoId(url) {
    // 匹配BV号
    const bvMatch = url.match(/BV[a-zA-Z0-9]{10}/);
    return bvMatch ? bvMatch[0] : null;
  }
}
